declare var form: any;
declare var map: any;

/**
 * 定义GIS地图加载辅助类(点击查询)
 */
export class GisPointSearchUtils {

    // 字典翻译服务
    private fs: any;
    // 地图数据
    private mapData: any;
    // 当前地图使用方案
    private curMap: string;
    // 此次操作是否为切换图层之后第一次
    private changeMap: boolean;
    // 属性查询对象
    private ss: any = null;
    // 元数据
    private metedata: string;
    // 弹窗显示数据
    showFields: any;
    // 弹窗显示数据过滤条件
    filterWhere = { key: true, name: 'sheng,shi' };
    // bool类型转换 false->是
    boolTransform = ['sfsh', 'sfwg'];
    // 所查询图层
    private layers = [];
    // 是否选中图层
    private isSelectMap = false;
    // 选中图层的id
    private featureId = '';
    private sourceId = '';
    private sourceLayer = '';
    private showDetail = false;
    // 通用对象
    option: {
        infoTemplateId?: string, // 弹窗id
        infoWindowHeight?: string, // 弹窗高度
        infoWindowWidth?: string, // 弹窗宽度
        infoWindowOverflow?: string // 弹窗滚动样式
        clickEvent?: any, // 弹窗点击事件回调
    } = {};

    constructor() {
        this.fs = form.FormDataService;
    }

    // 地图点击事件初始化
    init() {
        this.layersInit();

        const pmap = form.ConfigService.map;
        // 图层点击事件绑定
        pmap.on('click', (o: any) => {

            this.isSelectMap = false;
            // 变更方案后重新初始化数据
            if (this.curMap !== form.ConfigService.mapParas.styleId) {
                this.changeMap = true;
                this.layersInit();
            } else {
                this.changeMap = false;
            }

            const pixel = [o.point.x, o.point.y];
            // 按点线面图层id属性依次找
            // 使用some遍历直到某个条件符合返回true跳出循环
            this.layers.some(layer => {
                const feature = pmap.queryRenderedFeaturesByPixel(pixel, layer);
                if (feature && feature.length > 0) {

                    this.isSelectMap = true;
                    this.featureId = feature[0].id;
                    this.sourceLayer = feature[0].sourceLayer;
                    this.sourceId = feature[0].source;

                    // 组装feature对象
                    const ft: any = { type: feature[0].type, geometry: feature[0].geometry, properties: feature[0].properties };
                    this.option.infoTemplateId = feature[0].source + '-point-search';

                    this.mapData.sources.forEach(data => {
                        if (data.name === feature[0].layer.source) {
                            if (this.metedata !== data.metedata) {
                                //是否显示详情
                                if (feature[0].source.indexOf("doc") !== -1) {
                                    this.showDetail = true;
                                } else {
                                    this.showDetail = false;
                                }
                                this.metedata = data.metedata;
                                form.FormDataService.getMetadata(this.metedata, (e: any) => {
                                    this.showFields = this.filterFun(e, this.filterWhere);
                                    // 根据显示数据量设置弹窗样式
                                    this.option.infoWindowHeight = this.showFields.length > 12 ? '280px' : 'unset';
                                    this.option.infoWindowOverflow = this.showFields.length > 12 ? 'scroll' : 'unset';
                                    // tslint:disable-next-line: max-line-length
                                    document.getElementById('point-search-table-b').style.width = this.showFields.length > 12 ? 'unset' : '220px';
                                    this.option.clickEvent = (item, event) => {
                                        let inforId = item.properties.id
                                        // 阻止事件冒泡
                                        if (event) {
                                            event.stopPropagation();
                                        }
                                        // 基础数据跳转
                                        const sourceId = feature[0].source;
                                        const url = '#' + data.name + 'info_mis?info=true&id=' + inforId;
                                        const dom = document.getElementById(sourceId + '_info');
                                        if (!dom) {
                                            return;
                                        }
                                        const attr = document.createAttribute('href');
                                        attr.value = url;
                                        dom.setAttributeNode(attr);
                                    };
                                    this.startSearch(this.option, ft);
                                });
                            } else {
                                this.startSearch(this.option, ft);
                            }
                        }
                    });

                    return true;
                }
            });

            // 点击空白处清除高亮
            if (this.isSelectMap === false) {
                if (this.ss) {
                    this.ss.clear();
                }
            }
        });
    }

    // 图层初始化
    layersInit() {

        // 地图数据获取
        this.mapData = form.ConfigService.mapParas;
        // 当前地图方案
        this.curMap = this.mapData.styleId;

        this.layers = [];
        const newLayers: any = [];
        // 可查询的图层筛选
        this.mapData.layers.forEach(data => {
            if (data.leaf === true && data.type !== null) {
                this.mapData.sources.forEach(source => {
                    if (source.name === data.source && source.canSearch === true) {
                        newLayers.push(data);
                    }
                });
            }
        });
        // 图层排序
        newLayers.sort((a, b) => {
            // tslint:disable-next-line: no-unused-expression
            a.type.charCodeAt(0) - b.type.charCodeAt(0);
        });

        for (let i = newLayers.length - 1; i >= 0; i--) {
            this.layers.push(newLayers[i].id);
        }
    }

    // 数据过滤
    filterFun(data: any, filterWhere: any) {
        const filterData = [];
        data.forEach(item => {
            let isFilter = false;
            for (const key in filterWhere) {
                if (filterWhere.hasOwnProperty(key) === true) {
                    if (item.hasOwnProperty(key) === true) {
                        if (typeof filterWhere[key] === 'string') {
                            const values = filterWhere[key].split(',');
                            values.some(value => {
                                if (item[key] === value) {
                                    isFilter = true;
                                    return true;
                                }
                            });
                        } else {
                            if (item[key] === filterWhere[key]) {
                                isFilter = true;
                                return true;
                            }
                        }

                    }
                }
            }
            if (isFilter === false) {
                filterData.push(item);
            }
        });
        return filterData;
    }

    // 点查询服务初始化
    private initSearchService(option: any, initCall?: any) {
        map.Factory.SimpleSearch('AttributeSearch', (attributeSearch) => {
            attributeSearch.init('point-search', {
                infoTemplateId: option.infoTemplateId,
                infoWindowHeight: option.infoWindowHeight,
                infoWindowWidth: option.infoWindowWidth,
                infoWindowOverflow: option.infoWindowOverflow,
                clickEvent: option.clickEvent
            });
            if (initCall) {
                initCall(attributeSearch);
            }
        });
    }

    // 点查询服务重新初始化
    reInitSearchService(option: any) {
        this.ss.init('point-search', {
            infoTemplateId: option.infoTemplateId,
            infoWindowHeight: option.infoWindowHeight,
            infoWindowWidth: option.infoWindowWidth,
            infoWindowOverflow: option.infoWindowOverflow,
            clickEvent: option.clickEvent,
        });
    }

    // 开始查询
    startSearch(option: any, ft: any) {
        const that = this;
        if (this.ss) {
            this.reInitSearchService(option);
            this.showData(ft);
        } else {
            this.initSearchService(option, (service) => {
                that.ss = service;
                that.showData(ft);
            });
        }
    }

    // 点查询数据效果展示
    private showData(ft: any) {

        // 清除之前弹窗高亮
        this.clear();

        // 高亮
        if (ft.geometry.type !== 'Point' || ft.geometry.type !== 'MultiPoint') {
            const option = {
                layout: null,
                paint: null,
                filter: ["==", ["to-string", ["id"]], ["to-string", this.featureId]],
                sourceId: this.sourceId,
                sourceLayer: this.sourceLayer
            };
            this.ss.lineHighlight(ft, option);
        } else {
            this.ss.highlight(ft);
        }

        // 弹窗
        const that = this;
        this.dictionaryEscape(ft, (data: any) => {
            data.properties = that.transformNumber(data.properties);
            that.ss.info(data);
        });
    }

    // 属性翻译
    dictionaryEscape(ft: any, callback: any) {
        this.fs.dictionaryEscape(this.metedata, ft.properties, (data) => {
            for (const key in data) {
                if (data.hasOwnProperty(key) === true) {
                    if (key.indexOf('_Name') !== -1) {
                        const newKey = key.replace('_Name', '');
                        data[newKey] = data[key];
                        delete data[key];
                    }
                }
            }
            ft.properties = data;
            if (callback) {
                callback(ft);
            }
        });
    }

    // 属性处理
    transformNumber(obj: any): any {
        // 转数字类型、bool转义
        for (const key in obj) {
            let str = obj[key];
            if(str != null){
                str += ""
                str = str.replace(/\s+/g, '')
            }

            if(str === '' || str === 'null'){
                obj[key] = '无'
            }

            if(str.indexOf('.') !== -1){
                if (obj.hasOwnProperty(key) === true  &&  str !== '') {
                    const value = Number(obj[key]);
                    if (!isNaN(value)) {
                        obj[key] = value;
                    }
                }
            }

            if (this.boolTransform.includes(key) === true) {
                if (obj[key] !== null) {
                    if (obj[key] === true || obj[key] === 1) {
                        obj[key] = '是';
                    } else if (obj[key] === false || obj[key] === 0) {
                        obj[key] = '否';
                    }
                }

            }
        }
        return obj;
    }


    // 清除高亮弹窗
    clear() {
        if (this.ss) {
            this.ss.clear();

            // 切换方案render服务需要重新初始化
            if (this.changeMap === true) {
                this.ss.resetRenderService();
            }
        }
    }
}
